import axios from "axios";

// 创建一个 axios 对象出来
const axiosUtil = axios.create(
    {
        baseURL: 'http://localhost:8081/api',
        timeout: 5000
    }
)

// 自定义请求拦截器
axiosUtil.interceptors.request.use(
    config => {
        config.headers['Content-Type'] = 'application/json;charset=utf-8';
        const user = localStorage.getItem('user');
        // console.log("user=", user)
        if (user) {
            config.headers['token'] = JSON.parse(user).token;
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 自定义响应拦截器
axiosUtil.interceptors.response.use(
    response => {
        // response.data 后台返回的数据
        let res = response.data;
        // 字符串转 JSON
        if (typeof res === 'string') {
            res = res ? JSON.parse(res) : res
        }
        return res;
    },
    error => {
        return Promise.reject(error)
    }
)

export default axiosUtil;